package com.github.bryx.workflow.util;

import com.github.bryx.workflow.domain.process.runtime.TaskObjectAssignee;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Author jameswu
 * @Date 2021/7/9
 **/
public class WorkflowEngineUtil {
    public static List<TaskObjectAssignee> createTaskObjectAssignees(List<String> assigneeUserIs, List<String> assigneeGroupIds){
        if(CollectionsUtil.isNotEmpty(assigneeUserIs) || CollectionsUtil.isNotEmpty(assigneeGroupIds)){
            List<TaskObjectAssignee> taskObjectAssignees = Lists.newArrayList();
            if (CollectionsUtil.isNotEmpty(assigneeUserIs)){
                assigneeUserIs.forEach(userId->{
                    taskObjectAssignees.add(TaskObjectAssignee.builder().assigneeUserId(userId).build());
                });
            }
            if (CollectionsUtil.isNotEmpty(assigneeGroupIds)){
                assigneeGroupIds.forEach(groupId->{
                    taskObjectAssignees.add(TaskObjectAssignee.builder().assigneeGroupId(groupId).build());
                });
            }
            return taskObjectAssignees;
        }
        return null;
    }

    public static List<TaskObjectAssignee> createTaskObjectAssignees(String assigneeUserId){
        return Lists.newArrayList(TaskObjectAssignee.builder().assigneeUserId(assigneeUserId).build());
    }

    /**
     * 获取值为null的对象属性
     * @param obj
     * @return
     */
    public static String[] getNamesOfNullProperty(Object obj) {
        final BeanWrapper src = new BeanWrapperImpl(obj);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<>();
        for(PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    /**
     * 获取值为null的对象属性
     * @param obj
     * @return
     */
    public static String[] getNamesOfNonNullProperty(Object obj) {
        final BeanWrapper src = new BeanWrapperImpl(obj);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> names = new HashSet<>();
        for(PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue != null) names.add(pd.getName());
        }
        String[] result = new String[names.size()];
        return names.toArray(result);
    }
}
